package com.haoshuang.zhouzhoubang.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.haoshuang.zhouzhoubang.MyApp;
import com.haoshuang.zhouzhoubang.widget.camera.MySimpleCamera;
import com.luck.lib.camerax.CameraImageEngine;
import com.luck.lib.camerax.CustomCameraConfig;
import com.luck.lib.camerax.SimpleCameraX;
import com.luck.lib.camerax.listener.OnSimpleXPermissionDeniedListener;
import com.luck.lib.camerax.listener.OnSimpleXPermissionDescriptionListener;
import com.luck.lib.camerax.permissions.SimpleXPermissionUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.dialog.RemindDialog;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.engine.CropFileEngine;
import com.luck.picture.lib.engine.ImageEngine;
import com.luck.picture.lib.engine.UriToFileTransformEngine;
import com.luck.picture.lib.engine.VideoPlayerEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnCallbackListener;
import com.luck.picture.lib.interfaces.OnCameraInterceptListener;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnPermissionDeniedListener;
import com.luck.picture.lib.interfaces.OnPermissionDescriptionListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.interfaces.OnVideoThumbnailEventListener;
import com.luck.picture.lib.permissions.PermissionConfig;
import com.luck.picture.lib.permissions.PermissionUtil;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.DensityUtil;
import com.haoshuang.zhouzhoubang.R;
import com.luck.picture.lib.utils.PictureFileUtils;
import com.luck.picture.lib.utils.SandboxTransformUtils;
import com.luck.picture.lib.widget.MediumBoldTextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

public class ChooseMediaUtils {
    private final static String TAG_EXPLAIN_VIEW = "TAG_EXPLAIN_VIEW";
    private PictureSelectorStyle selectorStyle;
    private ImageEngine imageEngine;
    private Context context;

    public ChooseMediaUtils(Context context) {
        this.context = context;
        selectorStyle = new PictureSelectorStyle();
        imageEngine = GlideEngine.createGlideEngine();
        // 设置主题风格  微信风格
        setSelectorStyle();
        // 设置动画
        setAnimation();
    }

    /**
     * 单个图片选择 不包含拍照按钮
     */
    public void selectSingleImageWithoutCamera(OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofImage(), false, false, 1, 0, null, listener);
    }

    /**
     * 单个图片选择 包含拍照按钮
     */
    public void selectSingleImageWithCamera(OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofImage(), false, true, 1, 0, null, listener);
    }

    /**
     * 单个视频选择 不包含拍照按钮
     */
    public void selectSingleVideoWithoutCamera(OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofVideo(), false, false, 0, 1, null, listener);
    }

    /**
     * 单个图片选择 包含拍照按钮
     */
    public void selectSingleVideoWithCamera(OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofVideo(), false, true, 0, 1, null, listener);
    }

    /**
     * 多个图片选择 不包含拍照按钮
     *
     * @param maxSelectNum
     * @param listener
     */
    public void selectMultiImageWithoutCamera(int maxSelectNum, OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofImage(), true, false, maxSelectNum, 0, null, listener);
    }

    /**
     * 多个图片选择 包含拍照按钮
     *
     * @param maxSelectNum
     * @param listener
     */
    public void selectMultiImageWithCamera(int maxSelectNum, OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofImage(), true, true, maxSelectNum, 0, null, listener);
    }

    public void selectMultiVideoWithoutCamera(int maxSelectNum, List<LocalMedia> selectData, OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofVideo(), true, false, 0, maxSelectNum, selectData, listener);
    }

    public void selectMultiVideoWithCamera(int maxSelectNum, List<LocalMedia> selectData, OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofVideo(), true, true, 0, maxSelectNum, selectData, listener);
    }

    public void selectMultiMediaWithoutCamera(int maxSelectNum, int maxSelectVideoNum, List<LocalMedia> selectData, OnResultCallbackListener<LocalMedia> listener) {
        selectMedia(SelectMimeType.ofAll(), true, false, maxSelectNum, maxSelectVideoNum, selectData, listener);
    }

    /**
     * @param selectMimeType 媒体类型
     *                       图片：PictureMimeType.ofImage()
     *                       视频：PictureMimeType.ofVideo()
     *                       音频：PictureMimeType.ofAudio()
     *                       图片和视频：PictureMimeType.ofAll()
     * @param isMultiple     是否多选
     */
    public void selectMedia(int selectMimeType, boolean isMultiple, boolean isCamera, int maxSelectNum, int maxSelectVideoNum, List<LocalMedia> selectData, OnResultCallbackListener<LocalMedia> listener) {

        PictureSelector.create(getContext())
                .openGallery(selectMimeType)
                .setSelectorUIStyle(selectorStyle)
                .setImageEngine(imageEngine)
                .isWithSelectVideoImage(true)
//                .setCompressEngine(getCompressFileEngine())
                .setSandboxFileEngine(new MeSandboxFileEngine())
//                .setCameraInterceptListener(getCustomCameraEvent())
                .setPermissionDescriptionListener(getPermissionDescriptionListener())
                .setPermissionDeniedListener(getPermissionDeniedListener())
                .setVideoThumbnailListener(getVideoThumbnailEventListener())
                .setSelectionMode(isMultiple ? SelectModeConfig.MULTIPLE : SelectModeConfig.SINGLE)
                .isDisplayCamera(isCamera)
                .isMaxSelectEnabledMask(true)
                .setMaxSelectNum(maxSelectNum)
                .setMaxVideoSelectNum(maxSelectVideoNum)
                .setSelectedData(selectData)
                .forResult(listener);
    }

    /**
     * 直接打开相机 进行连续拍照
     * @param cameraMode
     * @param videoMaxCount
     * @param imageMaxCount
     * @param listener
     */
    public void openCamera(int cameraMode, int videoMaxCount, int imageMaxCount, OnResultCallbackListener<LocalMedia> listener) {

        String desc = "";
        String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
        if (cameraMode == CustomCameraConfig.BUTTON_STATE_BOTH){
            // 图片加视频
            desc = "相机权限使用说明\n用户app用于拍照/录视频, \n录音权限使用说明\n用户app用于采集声音";
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
            }else{
                permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            }
        }else if (cameraMode == CustomCameraConfig.BUTTON_STATE_ONLY_CAPTURE){
            // 图片
            desc = "相机权限使用说明\n用户app用于拍照/录视频,";
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                permission = new String[]{Manifest.permission.CAMERA};
            }else{
                permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            }
        }else{
            desc = "相机权限使用说明\n用户app用于拍照/录视频, \n录音权限使用说明\n用户app用于采集声音";
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
            }else{
                permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            }
        }

        PermissionHelper.INSTANCE.requestPermission(
                context,
                "权限说明",
                desc, permission, aBoolean -> {
                    if (aBoolean){
                        MySimpleCamera camera = MySimpleCamera.of();
                        camera.isAutoRotation(true);
                        camera.setCameraMode(cameraMode);
                        camera.setVideoFrameRate(25);
                        camera.setVideoBitRate(3 * 1024 * 1024);
                        camera.isDisplayRecordChangeTime(true);
                        camera.isManualFocusCameraPreview(true);
                        camera.isZoomCameraPreview(true);
                        camera.setOutputPathDir("");
                        camera.setPermissionDeniedListener(getSimpleXPermissionDeniedListener());
                        camera.setPermissionDescriptionListener(getSimpleXPermissionDescriptionListener());
                        camera.setVideoMaxCount(videoMaxCount);
                        camera.setImageMaxCount(imageMaxCount);
                        camera.setImageEngine(new CameraImageEngine() {
                            @Override
                            public void loadImage(Context context, String url, ImageView imageView) {
                                Glide.with(context).load(url).into(imageView);
                            }
                        });
                        camera.start(context, listener);
                    }
                    return null;
                });

    }

    /**
     * 权限拒绝后回调
     *
     * @return
     */
    private OnPermissionDeniedListener getPermissionDeniedListener() {
        return new MeOnPermissionDeniedListener();
    }


    /**
     * 权限拒绝后回调
     */
    private static class MeOnPermissionDeniedListener implements OnPermissionDeniedListener {

        @Override
        public void onDenied(Fragment fragment, String[] permissionArray,
                             int requestCode, OnCallbackListener<Boolean> call) {
            String tips;
            if (TextUtils.equals(permissionArray[0], PermissionConfig.CAMERA[0])) {
                tips = "缺少相机权限\n可能会导致不能使用摄像头功能";
            } else if (TextUtils.equals(permissionArray[0], Manifest.permission.RECORD_AUDIO)) {
                tips = "缺少录音权限\n访问您设备上的音频、媒体内容和文件";
            } else {
                tips = "缺少存储权限\n访问您设备上的照片、媒体内容和文件";
            }
            RemindDialog dialog = RemindDialog.buildDialog(fragment.getContext(), tips);
            dialog.setButtonText("去设置");
            dialog.setButtonTextColor(0xFF7D7DFF);
            dialog.setContentTextColor(0xFF333333);
            dialog.setOnDialogClickListener(new RemindDialog.OnDialogClickListener() {
                @Override
                public void onClick(View view) {
                    PermissionUtil.goIntentSetting(fragment, requestCode);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    private void setSelectorStyle() {
        // 主体风格
        SelectMainStyle numberSelectMainStyle = new SelectMainStyle();
        numberSelectMainStyle.setSelectNumberStyle(true);
        numberSelectMainStyle.setPreviewSelectNumberStyle(false);
        numberSelectMainStyle.setPreviewDisplaySelectGallery(true);
        numberSelectMainStyle.setSelectBackground(R.drawable.ps_default_num_selector);
        numberSelectMainStyle.setPreviewSelectBackground(R.drawable.ps_preview_checkbox_selector);
        numberSelectMainStyle.setSelectNormalBackgroundResources(R.drawable.ps_select_complete_normal_bg);
        numberSelectMainStyle.setSelectNormalTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_53575e));
        numberSelectMainStyle.setSelectNormalText(R.string.ps_send);
        numberSelectMainStyle.setAdapterPreviewGalleryBackgroundResource(R.drawable.ps_preview_gallery_bg);
        numberSelectMainStyle.setAdapterPreviewGalleryItemSize(DensityUtil.dip2px(getContext(), 52));
        numberSelectMainStyle.setPreviewSelectText(R.string.ps_select);
        numberSelectMainStyle.setPreviewSelectTextSize(14);
        numberSelectMainStyle.setPreviewSelectTextColor(ContextCompat.getColor(getContext(), R.color.white));
        numberSelectMainStyle.setPreviewSelectMarginRight(DensityUtil.dip2px(getContext(), 6));
        numberSelectMainStyle.setSelectBackgroundResources(R.drawable.ps_select_complete_bg);
        numberSelectMainStyle.setSelectText(R.string.ps_send_num);
        numberSelectMainStyle.setSelectTextColor(ContextCompat.getColor(getContext(), R.color.white));
        numberSelectMainStyle.setMainListBackgroundColor(ContextCompat.getColor(getContext(), R.color.black));
        numberSelectMainStyle.setCompleteSelectRelativeTop(true);
        numberSelectMainStyle.setPreviewSelectRelativeBottom(true);
        numberSelectMainStyle.setAdapterItemIncludeEdge(false);
        // 头部TitleBar 风格
        TitleBarStyle numberTitleBarStyle = new TitleBarStyle();
        numberTitleBarStyle.setHideCancelButton(true);
        numberTitleBarStyle.setAlbumTitleRelativeLeft(true);
        numberTitleBarStyle.setTitleAlbumBackgroundResource(R.drawable.ps_album_bg);

        numberTitleBarStyle.setTitleDrawableRightResource(R.drawable.ps_ic_grey_arrow);
        numberTitleBarStyle.setPreviewTitleLeftBackResource(R.drawable.ps_ic_normal_back);

        // 底部NavBar 风格
        BottomNavBarStyle numberBottomNavBarStyle = new BottomNavBarStyle();
        numberBottomNavBarStyle.setBottomPreviewNarBarBackgroundColor(ContextCompat.getColor(getContext(), R.color.ps_color_half_grey));
        numberBottomNavBarStyle.setBottomPreviewNormalText(R.string.ps_preview);
        numberBottomNavBarStyle.setBottomPreviewNormalTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_9b));
        numberBottomNavBarStyle.setBottomPreviewNormalTextSize(16);
        numberBottomNavBarStyle.setCompleteCountTips(false);
        numberBottomNavBarStyle.setBottomPreviewSelectText(R.string.ps_preview_num);
        numberBottomNavBarStyle.setBottomPreviewSelectTextColor(ContextCompat.getColor(getContext(), R.color.white));


        selectorStyle.setTitleBarStyle(numberTitleBarStyle);
        selectorStyle.setBottomBarStyle(numberBottomNavBarStyle);
        selectorStyle.setSelectMainStyle(numberSelectMainStyle);
    }

    private void setAnimation() {
        PictureWindowAnimationStyle defaultAnimationStyle = new PictureWindowAnimationStyle();
        defaultAnimationStyle.setActivityEnterAnimation(R.anim.ps_anim_enter);
        defaultAnimationStyle.setActivityExitAnimation(R.anim.ps_anim_exit);
        selectorStyle.setWindowAnimationStyle(defaultAnimationStyle);
    }

    private Context getContext() {
        return context;
    }

    /**
     * 权限说明
     *
     * @return
     */
    private OnPermissionDescriptionListener getPermissionDescriptionListener() {
        return new MeOnPermissionDescriptionListener();
    }

    /**
     * 添加权限说明
     */
    private static class MeOnPermissionDescriptionListener implements OnPermissionDescriptionListener {

        @Override
        public void onPermissionDescription(Fragment fragment, String[] permissionArray) {
            View rootView = fragment.requireView();
            if (rootView instanceof ViewGroup) {
                addPermissionDescription(false, (ViewGroup) rootView, permissionArray);
            }
        }

        @Override
        public void onDismiss(Fragment fragment) {
            removePermissionDescription((ViewGroup) fragment.requireView());
        }
    }

    /**
     * 自定义相机事件
     *
     * @return
     */
    private OnCameraInterceptListener getCustomCameraEvent() {
        return new MeOnCameraInterceptListener();
    }

    /**
     * 自定义拍照
     */
    private class MeOnCameraInterceptListener implements OnCameraInterceptListener {

        @Override
        public void openCamera(Fragment fragment, int cameraMode, int requestCode) {
            SimpleCameraX camera = SimpleCameraX.of();
            camera.isAutoRotation(true);
            camera.setCameraMode(cameraMode);
            camera.setVideoFrameRate(25);
            camera.setVideoBitRate(3 * 1024 * 1024);
            camera.isDisplayRecordChangeTime(true);
            camera.isManualFocusCameraPreview(true);
            camera.isZoomCameraPreview(true);
            camera.setOutputPathDir("");
            camera.setPermissionDeniedListener(getSimpleXPermissionDeniedListener());
            camera.setPermissionDescriptionListener(getSimpleXPermissionDescriptionListener());
            camera.setImageEngine(new CameraImageEngine() {
                @Override
                public void loadImage(Context context, String url, ImageView imageView) {
                    Glide.with(context).load(url).into(imageView);
                }
            });
            camera.start(fragment.requireActivity(), fragment, requestCode);
        }
    }

    /**
     * SimpleCameraX权限说明
     *
     * @return
     */
    private OnSimpleXPermissionDescriptionListener getSimpleXPermissionDescriptionListener() {
        return new MeOnSimpleXPermissionDescriptionListener();
    }

    /**
     * SimpleCameraX添加权限说明
     */
    private static class MeOnSimpleXPermissionDescriptionListener implements OnSimpleXPermissionDescriptionListener {

        @Override
        public void onPermissionDescription(Context context, ViewGroup viewGroup, String permission) {
            addPermissionDescription(true, viewGroup, new String[]{permission});
        }

        @Override
        public void onDismiss(ViewGroup viewGroup) {
            removePermissionDescription(viewGroup);
        }
    }

    /**
     * 添加权限说明
     *
     * @param viewGroup
     * @param permissionArray
     */
    private static void addPermissionDescription(boolean isHasSimpleXCamera, ViewGroup viewGroup, String[] permissionArray) {
        int dp10 = DensityUtil.dip2px(viewGroup.getContext(), 10);
        int dp15 = DensityUtil.dip2px(viewGroup.getContext(), 15);
        MediumBoldTextView view = new MediumBoldTextView(viewGroup.getContext());
        view.setTag(TAG_EXPLAIN_VIEW);
        view.setTextSize(14);
        view.setTextColor(Color.parseColor("#333333"));
        view.setPadding(dp10, dp15, dp10, dp15);

        String title;
        String explain;

        if (TextUtils.equals(permissionArray[0], PermissionConfig.CAMERA[0])) {
            title = "相机权限使用说明";
            explain = "相机权限使用说明\n用户app用于拍照/录视频";
        } else if (TextUtils.equals(permissionArray[0], Manifest.permission.RECORD_AUDIO)) {
            if (isHasSimpleXCamera) {
                title = "麦克风权限使用说明";
                explain = "麦克风权限使用说明\n用户app用于录视频时采集声音";
            } else {
                title = "录音权限使用说明";
                explain = "录音权限使用说明\n用户app用于采集声音";
            }
        } else {
            title = "存储权限使用说明";
            explain = "存储权限使用说明\n用户app写入/下载/保存/读取/修改/删除图片、视频、文件等信息";
        }
        int startIndex = 0;
        int endOf = startIndex + title.length();
        SpannableStringBuilder builder = new SpannableStringBuilder(explain);
        builder.setSpan(new AbsoluteSizeSpan(DensityUtil.dip2px(viewGroup.getContext(), 16)), startIndex, endOf, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(new ForegroundColorSpan(0xFF333333), startIndex, endOf, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        view.setText(builder);
        view.setBackground(ContextCompat.getDrawable(viewGroup.getContext(), R.drawable.ps_demo_permission_desc_bg));

        if (isHasSimpleXCamera) {
            RelativeLayout.LayoutParams layoutParams =
                    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.topMargin = DensityUtil.getStatusBarHeight(viewGroup.getContext());
            layoutParams.leftMargin = dp10;
            layoutParams.rightMargin = dp10;
            viewGroup.addView(view, layoutParams);
        } else {
            ConstraintLayout.LayoutParams layoutParams =
                    new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.topToTop = ConstraintSet.PARENT_ID;
            layoutParams.leftToLeft = ConstraintSet.PARENT_ID;
            layoutParams.leftMargin = dp10;
            layoutParams.rightMargin = dp10;
            viewGroup.addView(view, layoutParams);
        }
    }

    /**
     * 移除权限说明
     *
     * @param viewGroup
     */
    private static void removePermissionDescription(ViewGroup viewGroup) {
        View tagExplainView = viewGroup.findViewWithTag(TAG_EXPLAIN_VIEW);
        viewGroup.removeView(tagExplainView);
    }


    /**
     * SimpleCameraX权限拒绝后回调
     *
     * @return
     */
    private OnSimpleXPermissionDeniedListener getSimpleXPermissionDeniedListener() {
        return new MeOnSimpleXPermissionDeniedListener();
    }

    /**
     * SimpleCameraX添加权限说明
     */
    private static class MeOnSimpleXPermissionDeniedListener implements OnSimpleXPermissionDeniedListener {

        @Override
        public void onDenied(Context context, String permission, int requestCode) {
            String tips;
            if (TextUtils.equals(permission, Manifest.permission.RECORD_AUDIO)) {
                tips = "缺少麦克风权限\n可能会导致录视频无法采集声音";
            } else {
                tips = "缺少相机权限\n可能会导致不能使用摄像头功能";
            }
            RemindDialog dialog = RemindDialog.buildDialog(context, tips);
            dialog.setButtonText("去设置");
            dialog.setButtonTextColor(0xFF7D7DFF);
            dialog.setContentTextColor(0xFF333333);
            dialog.setOnDialogClickListener(new RemindDialog.OnDialogClickListener() {
                @Override
                public void onClick(View view) {
                    SimpleXPermissionUtil.goIntentSetting((Activity) context, requestCode);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    /**
     * 创建自定义输出目录
     *
     * @return
     */
    private String getVideoThumbnailDir() {
        File externalFilesDir = getContext().getExternalFilesDir("");
        File customFile = new File(externalFilesDir.getAbsolutePath(), "Thumbnail");
        if (!customFile.exists()) {
            customFile.mkdirs();
        }
        return customFile.getAbsolutePath() + File.separator;
    }

    /**
     * 处理视频缩略图
     */
    private OnVideoThumbnailEventListener getVideoThumbnailEventListener() {
        return new MeOnVideoThumbnailEventListener(getVideoThumbnailDir());
    }

    /**
     * 处理视频缩略图
     */
    private static class MeOnVideoThumbnailEventListener implements OnVideoThumbnailEventListener {
        private final String targetPath;

        public MeOnVideoThumbnailEventListener(String targetPath) {
            this.targetPath = targetPath;
        }

        @Override
        public void onVideoThumbnail(Context context, String videoPath, OnKeyValueResultCallbackListener call) {
            Glide.with(context).asBitmap().sizeMultiplier(0.6F).load(videoPath).into(new CustomTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    resource.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    FileOutputStream fos = null;
                    String result = null;
                    try {
                        File targetFile = new File(targetPath, "thumbnails_" + System.currentTimeMillis() + ".jpg");
                        fos = new FileOutputStream(targetFile);
                        fos.write(stream.toByteArray());
                        fos.flush();
                        result = targetFile.getAbsolutePath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        PictureFileUtils.close(fos);
                        PictureFileUtils.close(stream);
                    }
                    if (call != null) {
                        call.onCallback(videoPath, result);
                    }
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {
                    if (call != null) {
                        call.onCallback(videoPath, "");
                    }
                }
            });
        }
    }

    /**
     * 压缩引擎
     *
     * @return
     */
    private ImageFileCompressEngine getCompressFileEngine() {
        return new ImageFileCompressEngine();
    }

    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {

        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).filter(new CompressionPredicate() {
                @Override
                public boolean apply(String path) {
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        return true;
                    }
                    return !PictureMimeType.isUrlHasGif(path);
                }
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }

    /**
     * 自定义沙盒文件处理
     */
    private static class MeSandboxFileEngine implements UriToFileTransformEngine {

        @Override
        public void onUriToFileAsyncTransform(Context context, String srcPath, String mineType, OnKeyValueResultCallbackListener call) {
            if (call != null) {
                call.onCallback(srcPath, SandboxTransformUtils.copyPathToSandbox(context, srcPath, mineType));
            }
        }
    }
}
